import http,pdb,re,MySQLdb,magic
from .. import config
from . import postutils


def upload(handler):
    handler.send_response(http.HTTPStatus.OK)
    handler.send_header('Content-type','html')
    handler.send_header('Encoding','utf-8')
    handler.end_headers()
    with open('sites/upload.html','rb') as upload_site:
        handler.wfile.write(upload_site.read())

def handle_uploaded_data(handler):
    try:
        parsed=postutils.parse(handler)
        name=parsed[1]
        images_posted=parsed[2:-1]
        name,*images=postutils.get_content(name,*images_posted)
        name=name.decode()
        assert config.dangers.match(name)==None
        save_image(name,images)
        handler.send_response(http.HTTPStatus.SEE_OTHER)
        handler.send_header('Location','/')
        handler.end_headers()
    except BaseException:
        handler.send_response(http.HTTPStatus.INTERNAL_SERVER_ERROR)
 
def save_image(uploader,images):
    db=MySQLdb.connect('localhost','ken','ken0417','images')
    cursor=db.cursor()
    db.autocommit(True)
    cursor.execute('select id from images')
    ids=cursor.fetchall()
    fileindex=ids[-1][0]+1
    for image in images:
        fileext=magic.from_buffer(image,mime=True).split('/')[-1]
        filename=config.opj(config.image_path,str(fileindex)+'.'+fileext)
        with open(filename,'wb') as image_file:
            image_file.write(image)
        cursor.execute('insert into images (uploader,time,filename) value ("{uploader}",now(),"{filename}");'
                .format(uploader=uploader,filename=filename))
        fileindex+=1
    db.close()


